<?php
class Admin_RegionArticleController extends Apps_Controller_Action_Admin {

	//LIST
	public function indexAction() {
		$this->actResolve('act_delete',
						  'delete', null, null, array('id' => $this->_getParam('item_checker')),
					 	  true);

		$tbArticle = new M_DbTable_Article();
		$grid 	= new Apps_Plugin_Grid('EventGrid');

		$grid->setData($tbArticle->getListRegionArticle())
			 ->setTableCaption('List article about region')
			 ->setTableColumnFormat(array(
			 		array('title'		=> 'STT',
			 			  'dataField'	=> '_rank_',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'ID',
			 			  'dataField'	=> 'id',
			 			  'class'		=> 'center'),
			 		array('title'		=> 'Country',
			 			  'dataField'	=> 'country_name'),
			 		array('title'		=> 'Region',
			 			  'dataField'	=> 'region_name'),
			 		array('title'		=> 'Article\'s name',
			 			  'dataField'	=> 'title'),
			 		array('title'		=> 'Description',
			 			  'dataField'	=> 'description'),
			 		array('title'		=> 'Article\'s type ',
	                      'html'        => function($rs) {
	                                            $labelRegionArticleType = new Apps_View_Helper_LabelRegionArticleType();
	                                            return $labelRegionArticleType->labelRegionArticleType($rs['type']);
	                                        },
			 			  'class'		=> 'center'),
			 		array('title'       => 'Edit',
			 			  'html'        => array('<a href="/admin/region-article/edit?id=%s"><i class="icon-edit" title="Sửa"></i></a>',
			 			  				   array('id')),
			 			  'width'       => '2%')
			 		));
		$this->view->grid = $grid;
	}

	//ADD
	public function addAction() {
		$rq 		= $this->_request;
		$f 			= new Admin_Form_AddRegionArticle();
		$tbArticle 	= new M_DbTable_Article();

		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				// Upload thumbnail
				$uploader = new Apps_Plugin_Upload_File();
				$uploader->setMaxQuantity(1)
						 ->setSubCategory(Apps_Plugin_Upload_File::CAT_ARTICLE);
				$thumbnail = ($uploaded = $uploader->upload())
						 	 ? $uploaded['thumbnail']['uri']
						 	 : null;

				//resize images
				try {
				    $image = new Apps_Plugin_ResizeImages();
				    $image->load(PUBLIC_PATH .$thumbnail);
				    $image->resizeToWidth(200);
				    $image->save(PUBLIC_PATH .$thumbnail);
				} catch (Exception $e) {
				    //Excetion here
				}

				$data = $f->getValues();
				$regionId = $f->getValue('reference_id');
				if(!$regionId || $regionId == '' || $regionId == '0') {
// 					$f->getElement('country')->set
					$f->getElement('reference_id')->addError('Value cannot be empty !');
				} else {
					$data['thumbnail'] = $thumbnail;
					$data['reference_type'] = M_DbTable_Article::REFERENCE_TYPE_REGION;
					$keyFilter = array('title',
										'en_title',
										'overview',
										'en_overview',
										'detail',
										'en_detail',
										'reference_id',
										'reference_type',
										'description',
										'type',
										'thumbnail');
					$this->_flashMessenger->addMessage(
						$tbArticle->safelyInsert($data, $keyFilter)
						? self::$msgAddSuccess
						: self::$msgAddFailed
					);
					$this->_helper->redirector('index', null, null);
				}
			}
		}
		$this->view->form = $f;
	}

	//EDIT
	public function editAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');
		$tbArticle = new M_DbTable_Article();
		$article 	= $tbArticle->getArticleById($id)->query()->fetch();

		if (!$id || !$article) {
			$this->_helper->redirector('index');
		}

		$f = new Admin_Form_AddRegionArticle();
		if ($rq->isPost()) {
			if ($f->isValid($rq->getParams())) {
				$tbArticle 	= new M_DbTable_Article();

				// Upload thumbnail - replace thumbnail if changed
				$thumbnail = $article['thumbnail'];

				if(Apps_Plugin_Upload_File::isUploaded('thumbnail')) {
					$uploader = new Apps_Plugin_Upload_File();
					$uploader->setMaxQuantity(1)
							 ->setSubCategory(Apps_Plugin_Upload_File::CAT_ARTICLE);

					$uploaded = $uploader->upload();
					if($uploaded) {
						unlink(Apps_Plugin_Upload_File::getPath($thumbnail)); // Delete ex-thumbnail
						$thumbnail = $uploaded['thumbnail']['uri'];
						//resize images
						try {
						    $image = new Apps_Plugin_ResizeImages();
						    $image->load(PUBLIC_PATH .$thumbnail);
						    $image->resizeToWidth(200);
						    $image->save(PUBLIC_PATH .$thumbnail);
						} catch (Exception $e) {
						    //Excetion here
						}
					}
				}

				$data = $f->getValues();
				$data['thumbnail'] 			 = $thumbnail;
				$where['id = ?'] 	 		 = $id;
				$where['reference_id = ?'] 	 = $article['reference_id'];
				$where['reference_type = ?'] = M_DbTable_Article::REFERENCE_TYPE_REGION;
				$r = $tbArticle->safelyUpdate($data, $where);
				$this->_flashMessenger->addMessage(
						$r
						? self::$msgUpdateSuccess
						: self::$msgUpdateFailed
				);
				$this->_helper->redirector('index');
			}
		}
		$f->setLegend('Update info of article about region');
		$f->populate($article);
		$this->view->form = $f;
		$this->render('add');
	}

	//DELETE
	public function deleteAction() {
		$rq = $this->_request;
		$id = $rq->getParam('id');
		$tbArticle = new M_DbTable_Article();

		if (!$id) {
			$this->_helper->redirector('index');
		}

		if (is_numeric($id)) {
			$article = $tbArticle->getArticleById($id)->query()->fetch();
			$this->_flashMessenger->addMessage(
				$tbArticle->safelyDelete(array('id = ?' => $id, 'reference_type =?' => M_DbTable_Article::REFERENCE_TYPE_REGION))
				? self::$msgDeleteSuccess
				: self::$msgDeleteError
			);
			unlink(Apps_Plugin_Upload_File::getPath($article['thumbnail']));
		} elseif (is_array($id)) {
			foreach ($id as $v) {
				$article = $tbArticle->getArticleById($v)->query()->fetch();
				$tbArticle->safelyDelete(array('id = ?' => $v, 'reference_type =?' => M_DbTable_Article::REFERENCE_TYPE_REGION));
				unlink(Apps_Plugin_Upload_File::getPath($article['thumbnail']));
			}
		}

		$this->_helper->redirector('index');
	}

}